# !/usr/bin/env python
# _*_ coding: utf-8 _*_
"""
Time      : 2019/8/19 12:02
@Author   : gao
@Site     : 
@File     : write_data2file_thread.py
@Software : PyCharm
"""
import csv
from PySide6.QtCore import *
import ast

'''由于数据的写入属于耗时的IO操作，所以将这种操作放到单独的线程中进行'''


class Signal(QObject):
    finishSignal = Signal(int)


class WriteDataToFile(QRunnable):
    def __init__(self, file_path, header, content):
        super(WriteDataToFile, self).__init__()
        self.signal = Signal()
        self.file_path = file_path
        self.header = header
        self.content = content
        self.flag = True

    def run(self):
        try:
            if self.flag:
                with open(self.file_path, 'w', newline='', encoding="utf_8_sig") as csvfile:
                    writer = csv.writer(csvfile)
                    # 写入表格的标题
                    writer.writerow(self.header)
                    # 循环写入表格的内容
                    for i in range(len(self.content)):
                        writer.writerow(self.content[i])
        except PermissionError as e:
            self.signal.finishSignal.emit(2)
        except Exception as e:
            self.signal.finishSignal.emit(0)
        else:
            self.signal.finishSignal.emit(1)

    def cancel_thread(self):
        self.flag = False
